﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;

namespace Project2.多线程
{
    //https://zhuanlan.zhihu.com/p/119074326
    //https://blog.csdn.net/qq_44705559/article/details/117382445
    internal class ThreadStudy
    {
        private static void DownLoad()
        {
            Console.WriteLine("DownLoad Begin " + Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(1000);//等待一秒
            Console.WriteLine("DownLoad End");
        }

        private static void WriteText(string text)
        { Console.WriteLine(text); }

        private static void DownLoad2(object name)//参数必须是引用类型
        {
            Console.WriteLine("DownLoad Begin " + name);
            Thread.Sleep(1000);
            Console.WriteLine("DownLoad End" + name);
        }

        private static void MainThreadStudy(string[] args)
        {
            //创建Thread对象
            Thread thread = new Thread(DownLoad);
            //启动线程
            thread.Start();
            Console.WriteLine("Main1");

            //创建Thread对象
            Thread thread2 = new Thread(DownLoad2);
            //启动线程
            thread2.Start("DownLoad2");
            Console.WriteLine("Main2");

            Thread thread3 = new Thread(() => WriteText("Hello"));
            thread3.Start();

            Thread.CurrentThread.Name = "main3";

            Thread worker = new Thread(Go);

            worker.Name = "worker";

            worker.Start();

            Go();

            //创建Thread对象
            Thread thread4 = new Thread(DownLoad2);
            Console.WriteLine("t4线程状态 :" + thread4.ThreadState.ToString());
            //启动线程
            thread4.Start("DownLoad4");
            Console.WriteLine("t4线程状态 :" + thread4.ThreadState.ToString());
            thread4.Join();//等待下载全部完成，再执行主程序
            Console.WriteLine("t4线程状态 :" + thread4.ThreadState.ToString());
            Console.WriteLine("Main4");
            Console.WriteLine("t4线程状态 :" + thread4.ThreadState.ToString());
        }

        private static void Go()
        {
            Console.WriteLine("Hello from " + Thread.CurrentThread.Name);
        }
    }
}